<?php
/**
 * 大概写了一下,还需要细化，可以根据配置信息是否启用多线程，还可以配置一次多少信息等等
 * User: wiggin
 * Date: 2017/11/22
 * Time: 10:54
 */

namespace App\Model;

use App\Utility\Db\Redis;
use App\Utility\Logis\Wenhui\WenHuiLogis;
use App\Utility\SysConst;
use Core\Component\Di;
use Core\Component\Logger;

class WhPackageTask
{
    public function handler($taskData)
    {
        Logger::getInstance("wh")->console("wh_start");
        $return = array();
        try {
            //getData
            $packageList = $this->getData();
            Logger::getInstance("wh")->console("wh_data" . count($packageList));
            $db = Di::getInstance()->get(SysConst::MYSQL);
            if ($packageList) {
                if ($taskData['task_thread'] > 1) { //增加多进程处理
                    $workers = [];
                    $chunk = ceil(count($packageList) / $taskData['task_thread']);
                    $packageList = array_chunk($packageList, $chunk);
                    $returnKey = $taskData['task_thread_return'];
                    for ($i = 0; $i < $taskData['task_thread']; $i++) {
                        $data = $packageList[$i];
                        $process = new \swoole_process(function (\swoole_process $process) use ($data, $returnKey) {
                            Logger::getInstance("process")->console("process_info" . serialize($data) . 'pid' . $process->pid);
                            $return1 = array();
                            foreach ($data as $val) {
                                $requestData = array('reference_no' => $val['track_num'], 'label_type' => 1, 'order_type' => 3);
                                $labelResult = WenHuiLogis::getInstance()
                                    ->setRequestBody($requestData)
                                    ->setSoapMethod('getLabelUrl')
                                    ->setSendMethod('callService')
                                    ->sendRequest()
                                    ->getResponse();
                                $up = array(
                                    'get_label_time' => date('Y-m-d H:i:s')
                                );
                                if ($labelResult['status']) {
                                    $up['print_label'] = isset($labelResult['data']->url) ? $labelResult['data']->url : 'NULL';
                                }
                                $return1[$val['package_id']] = serialize($up);
                                //$return[$val['package_id']] = $db->where("package_id = '{$val['package_id']}'")->update('ueb_order_package', $up);
                            }
                            Redis::getInstance()->hMSet($returnKey, $return1);
                            $process->exit();
                        }, false, false);
                        $pid = $process->start();
                        $workers[$pid] = $process;
                    }
                    foreach ($workers as $key => $val) {
                        $return[$key] = \swoole_process::wait();
                    }
                    //获取所有的返回数据队列
                    $returnList = Redis::getInstance()->hGetAll($returnKey);
                    if ($returnList) {
                        $db = Di::getInstance()->get(SysConst::MYSQL);
                        foreach ($returnList as $key => $val) {
                            $up = unserialize($val);
                            $return[$key] = $db->where("package_id = '{$key}'")->update('ueb_order_package', $up);
                        }
                    }
                    /*foreach($workers as $process){
                        //子进程也会包含此事件
                        swoole_event_add($process->pipe, function ($pipe) use($process){
                            $data = $process->read();
                            echo "RECV: " . $data.PHP_EOL;
                        });
                    }*/
                } else {
                    foreach ($packageList as $val) {
                        $requestData = array('reference_no' => $val['track_num'], 'label_type' => 1, 'order_type' => 3);
                        $labelResult = WenHuiLogis::getInstance()
                            ->setRequestBody($requestData)
                            ->setSoapMethod('getLabelUrl')
                            ->setSendMethod('callService')
                            ->sendRequest()
                            ->getResponse();
                        $up = array(
                            'get_label_time' => date('Y-m-d H:i:s')
                        );
                        if ($labelResult['status']) {
                            $up['print_label'] = isset($labelResult['data']->url) ? $labelResult['data']->url : 'NULL';
                        }
                        $return[$val['package_id']] = $db->where("package_id = '{$val['package_id']}'")->update('ueb_order_package', $up);
                    }
                }
            }
        } catch (\Exception $e) {
            $return = 'Exception: file=>' . $e->getFile() . ';code=>' . $e->getCode() . ';line=>' . $e->getLine() . ';message=>' . $e->getMessage();
        }
        Logger::getInstance("wh")->console("wh_return" . serialize($return));
        return $return;
    }

    public function getData()
    {
        $db = Di::getInstance()->get(SysConst::MYSQL);
        $packageList = $db->select('package_id,ship_code,track_num,track_num2')
            ->where('print_label = "" AND ship_code in ("cm_els_wh")')
            ->limit(5)
            ->from('ueb_order_package');
        return $packageList;
    }
}